const {baseUrl,CODE} = require('../../config/api.js')
const app = getApp()
Component({
  properties: {
    info: {
      type: Object,
      value: {}
    }
  },
  data: {
    comments: [],
    userInfo: {}
  },
  attached() {
    this.getComments()
    if (Object.keys(app.globalData.userInfo).length > 0) {
      this.setData({
        userInfo: app.globalData.userInfo,
      })
    } else {
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
        })
      }
    }
  },
  methods: {
    // 请求评论
    getComments() {
      wx.request({
        url: baseUrl + '/api/comments',
        method: 'GET',
        data: {
          postid: this.data.info.postInfo.id
        },
        success: (res) => {
          res = res.data
          if (res.code === CODE && res.data) {
            this._nomalizeData(res.data)
          }
        },
        fail: (err) => {
          console.log(err)
        }
      })
    },
    onRemark(options) {
      const { id } = options.target.dataset
      // console.log(options)
      const params = {
        postId: id,
        parentId: '',
        toUserId: this.data.info.userInfo.id
      }
      this.triggerEvent('remark', params)
    },
    onChildRemark(params) {
      this.triggerEvent('remark', params.detail)
    },
    onDelete(options) {
      const {id} = options.target.dataset
      this.triggerEvent('delete', {id})
    },
    // 新增评论的成功的回调
    onSuccess(data) {
      const arr = this.data.comments.slice()
      // Todo: 得到被回复得parentId, 找到comments数组中对应得位置，然后插入进去
      const idx = arr.findIndex((item) => {
        return item.id == data.parentId
      })
      if (idx < 0) {
        arr.push(data)
      } else {
        data.indent = arr[idx].indent + 15
        // console.log(data)
        arr.splice((idx + 1), 0, data)
      }
      this.setData({
        comments: arr
      })
    },
    _nomalizeData(newVal) {
      //执行递归
      const arr = this._recursion(newVal)
      this.setData({
        comments: arr
      })
    },
    _recursion(arr) {
      let ret = [];
      (function fn(arr, indent) {
        arr.forEach((item) => {
          ret.push(item)
          item.indent = indent || 0
          if (Array.isArray(item.children)) {
            fn(item.children, item.indent + 15)
          }
        })
      })(arr)
      return ret
    }
  }
})
